/*
 * Copyright (c) 2007 Compl Yue Still, All Rights Reserved.
 */

/**
 * 
 */
package hbi.wire.java.host;

import hbi.domain.java.JavaDomain;
import hbi.java.util.CharSetConstants;

import java.io.IOException;
import java.nio.ByteBuffer;

class MethodConstant implements IncomingTag
{
    private final ResolvedType type;

    MethodConstant(ResolvedType type)
    {
        this.type = type;
    }

    private byte[] read = null;

    private int readPos = 0;

    public boolean processIncomingData(ByteBuffer buffer) throws IOException
    {
        if (read == null)
        // method name length not read yet
        {
            if (buffer.remaining() < 2)
            // length not available yet
                return false;

            int len = buffer.getShort() & 0xFFFF;
            if (len <= 0) throw new SecurityException("Empty method name");
            if (len > JavaDomain.MAX_TYPE_NAME_LENGTH)
                throw new SecurityException(
                    "Banged with extreme long method name of " + len
                        + " chars.");
            read = new byte[len];
        }

        assert readPos < read.length : "or we should have finished";
        int len = Math.min(read.length - readPos, buffer.remaining());
        if (len > 0)
        {
            buffer.get(read, readPos, len);
            readPos += len;
            if (readPos >= read.length)
            {
                type.resolveMethod(new String(read, CharSetConstants.UTF8));
                return true;
            }
        }

        return false;
    }

}
